package RiverCrossingMinigame;
import Game.GameDriver;
// Some code was adapted from the Virginia CS homework assignments and 
// tutorials/examples/explanations found here http://www.cs.virginia.edu/cs201j/problem-sets/ps5/

import javax.swing.*;

import GUIInterfaces.OregonPanel;
import GUIInterfaces.OregonWindow;

import java.awt.*;
import java.awt.event.*;

/**
 * THis class represents the panel that holds the river crossing minigame, this class is 
 * responsible for redrawing the grid and taking player input to play the game
 * 
 * @author Ray DeCuir
 * @version 1.0
 *
 */

public class GamePanel extends JPanel implements KeyListener, OregonPanel {
	
	// The backing grid used to move the pieces around
	private Grid grid;

	// The player object
	static Vehicle player;
	String property = "lose";
	volatile static boolean crash = false;
	OregonWindow parent;
	// Constructor that takes in the siez of the panel and the grid object to be used. 
	public GamePanel (int width, int height, Grid grid,OregonWindow parent) 
	{
		setLayout (new BorderLayout ());
		this.parent = parent;
		this.grid = grid;
		player = new Vehicle();
		try {
			grid.setObjectAt(10,8,player);
			player.init(10,8,grid);	
		}
		catch(Exception e) { }

		addKeyListener(this);
		add (grid, BorderLayout.CENTER);
		
		for (int i = 2 ; i < 7 ; i++ )
		{
			new Lane(grid, i);
		}
	}
	
	
	// Methods needed in the KeyListener interface
	public void keyReleased (KeyEvent e) {  }
	public void keyTyped (KeyEvent e) {  }
	
	/**
	 * This method captures the players key inputs and translates them into the 
	 * players movements
	 * 
	 */
	
	public void keyPressed(KeyEvent e) 
	{
		int xloc = player.getX();
		int yloc = player.getY();
		// move the player if possible for the grid
		if (e.getKeyCode() == KeyEvent.VK_DOWN && yloc < 8){
			yloc++;
		}
		else if (e.getKeyCode() == KeyEvent.VK_UP && yloc > 0){
			yloc--;
		}
		else if (e.getKeyCode() == KeyEvent.VK_RIGHT && xloc < 19){
			xloc++;
		}
		else if (e.getKeyCode() == KeyEvent.VK_LEFT && xloc > 0){
			xloc--;
		} 
		else {
		}

		
		// move the player
		synchronized (grid){
			try{
				player.setLocation (xloc, yloc);
			}
			catch(RuntimeException e2){ 
				
				player.lose();
				property = "lose";
				xloc = 10;
				yloc = 8;
				player.setLocation(xloc, yloc);
				parent.done(this);
			}
		}
		
		grid.repaint();
		if (player.win()) {
			xloc = 10;
			yloc = 8;
			player.setLocation(xloc, yloc);
			property = "win";
			parent.done(this);
		}
	}
	

	@Override
	public String getProperty() {
		// TODO Auto-generated method stub
		return property;
	}


	@Override
	public GameDriver getGameDriver() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void setGameDriver(GameDriver gd) {
		// TODO Auto-generated method stub
		
	}


	
}

